package com.kkb.proxy.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import com.kkb.proxy.statix.AOP;
import com.kkb.service.IService;

/**
 * JDK 动态代理工厂
 *
 * @author ztranscript 2021/8/28 14:47
 **/
public class JdkProxyFactory {
    /**
     * 目标对象
     */
    private IService service;
    /**
     * 切面
     */
    private AOP aop;

    public JdkProxyFactory(IService service, AOP aop) {
        this.service = service;
        this.aop = aop;
    }

    /**
     * 获取JDK动态代理实例
     *
     * @return jdkProxy
     */
    public Object getProxyInstance() {
        return Proxy.newProxyInstance(
                service.getClass().getClassLoader(),
                service.getClass().getInterfaces(),
                new ProxyHandler()
        );
    }

    private class ProxyHandler implements InvocationHandler {
        /**
         * 拦截被代理类方法,增强其功能
         *
         * @param proxy  代理类
         * @param method 拦截方法
         * @param args   方法入参
         * @return 方法返回值
         * @throws Throwable 异常
         */
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            try {
                aop.before();
                /**
                 * 核心业务
                 */
                Object invoke = method.invoke(service, args);
                aop.after();
                return invoke;
            } catch (Exception e) {
                aop.exception();
                e.printStackTrace();
                throw e;
            } finally {
                aop.myFinally();
            }
        }
    }
}
